package com.org.litepal.slice.manager;

import com.org.litepal.ResourceTable;
import com.org.litepal.provider.StringItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.RoundProgressBar;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.litepal.tablemanager.Connector;
import org.litepal.util.DBUtility;

import java.util.ArrayList;
import java.util.List;

public class TableListAbilitySlice extends AbilitySlice {
    private RoundProgressBar progressBar;

    private ArrayList<String> mList = new ArrayList<>();
    private StringItemProvider itemProvider;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_table_list);

        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_listTable);
        progressBar = (RoundProgressBar) findComponentById(ResourceTable.Id_pbTable);
        progressBar.setDividerLineThickness(3);
        progressBar.setIndeterminate(true);


        itemProvider = new StringItemProvider(mList, this.getContext());
        listContainer.setItemProvider(itemProvider);

        populateTables();

        listContainer.setItemClickedListener((listContainer1, component, i, l) -> {
            Intent intentStart = new Intent();
            intentStart.setParam(TableStrutureAbilitySlice.TABLE_NAME,mList.get(i));
            present(new TableStrutureAbilitySlice(),intentStart);
        });
    }
    private void populateTables() {
        progressBar.setVisibility(Component.VISIBLE);
        new Thread(() -> {
            List<String> tables = DBUtility.findAllTableNames(Connector.getDatabase());
            for (String table : tables) {
                if (table.equalsIgnoreCase("Harmony_metadata")
                        || table.equalsIgnoreCase("sqlite_sequence")
                        || table.equalsIgnoreCase("table_schema")) {
                    continue;
                }
                mList.add(table);
            }


            handler.postTask(() -> {
                progressBar.setVisibility(Component.HIDE);
                itemProvider.notifyDataChanged();
            });

        }).start();
    }
    private EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeAllEvent();
    }
}